from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas import customer as schemas
from app.database.models.erp import CustomerProfile
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.CustomerProfile])
def get_customers(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_agent_user),
    skip: int = 0,
    limit: int = 100
):
    """获取客户列表"""
    customers = db.query(CustomerProfile)\
        .filter(CustomerProfile.work_area_id == current_user.workarea_id)\
        .offset(skip)\
        .limit(limit)\
        .all()
    return customers

@router.post("/", response_model=schemas.CustomerProfile)
def create_customer(
    *,
    db: Session = Depends(deps.get_db),
    customer_in: schemas.CustomerProfileCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新客户"""
    try:
        # 设置工作区
        if not customer_in.work_area_id:
            customer_in.work_area_id = current_user.workarea_id

        # 检查权限
        if current_user.role != "admin" and customer_in.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        customer = CustomerProfile(**customer_in.dict())
        db.add(customer)
        db.commit()
        db.refresh(customer)
        return customer
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{customer_id}", response_model=schemas.CustomerProfile)
def update_customer(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    customer_in: schemas.CustomerProfileUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新客户信息"""
    try:
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        update_data = customer_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(customer, field, value)

        db.add(customer)
        db.commit()
        db.refresh(customer)
        return customer
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{customer_id}", response_model=schemas.CustomerProfile)
def get_customer(
    customer_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取客户详情"""
    try:
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_id).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        return customer
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))